package com.wchen.nio.capter3_2;

import com.wchen.nio.capter2_3.TimeClientHandle;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @作者： wchen
 * @描述：
 * @创建时间： 2018/7/30 20:48
 * @版本：Copyright 2018, Inc. All Rights Reserved.
 * @修改信息：
 */
public class TimeClient {

    public void connect(int port, String host) throws Exception{
        //配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new StringEncoder())
                                    .addLast(new StringDecoder())
                                    .addLast(new TimeClientHandle3());
                        }
                    });
            //发起异步连接操作
            ChannelFuture f = bootstrap.connect(host, port);

//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
//            while(true){
//                System.out.println("请输入：");
//                String msg = bufferedReader.readLine();
//                f.channel().writeAndFlush(msg);
//            }

            //等待客户端链路关闭
            f.channel().closeFuture().sync();

        }finally {
            //退出，释放NIO线程组
            group.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws Exception {
        int port = 8080;
        if(args != null && args.length > 0){
            try {
                port = Integer.valueOf(args[0]);
            }catch (NumberFormatException e){
                e.printStackTrace();
            }
        }
        new TimeClient().connect(port, "127.0.0.1");

    }
}
